<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['erp:product:create']"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      新增
    </el-button>
    <!--    <el-button-->
    <!--      type="danger"-->
    <!--      plain-->
    <!--      :disabled="isEmpty(checkedIds)"-->
    <!--      @click="handleDeleteBatch"-->
    <!--      v-hasPermi="['erp:product:delete']"-->
    <!--    >-->
    <!--      <Icon icon="ep:delete" class="mr-5px" /> 批量删除-->
    <!--    </el-button>-->
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
        size="small"
    >
      <el-table-column type="selection" width="55"/>
      <!--      <el-table-column label="产品编号" align="center" prop="id" />-->
      <el-table-column label="产品名称" align="center" prop="productName"/>
      <el-table-column label="产品商品编码" align="center" prop="productBarCode"/>
      <el-table-column label="单位" align="center" prop="unitName"/>
      <el-table-column label="产品分类" align="center" prop="categoryName"/>
      <el-table-column label="产品属性" align="center" prop="property">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_PRODUCT_PROPERTY" :value="scope.row.property"/>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source"/>

<!--      <el-table-column label="周期（天）" align="center" prop="cycle"/>-->
<!--      <el-table-column label="安全库存" align="center" prop="safeStock"/>-->
      <!--      <el-table-column label="产品规格" align="center" prop="standard" />-->

      <!--      <el-table-column label="基础重量（kg）" align="center" prop="weight" />-->
<!--      <el-table-column label="成本价" align="center" prop="costPrice"/>-->
<!--      <el-table-column label="当前库存" align="center" prop="stockCount"/>-->
      <el-table-column label="数量" align="center" prop="count"/>
<!--      <el-table-column label="费用" align="center" prop="cost"/>-->
      <el-table-column label="产品备注" align="center" prop="remark"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['erp:product:update']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['erp:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <ProductBomMaterialForm ref="formRef" @success="getList"/>
</template>
<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import {ProductApi, ProductBomMaterial} from '@/api/erp/product/product'
import ProductBomMaterialForm from './ProductBomMaterialForm.vue'
import {DICT_TYPE} from "@/utils/dict";

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const props = defineProps<{
  parentId?: number // 父产品商品编码（主表的关联字段）
}>()
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  parentId: undefined as unknown
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
    () => props.parentId,
    (val: number) => {
      if (!val) {
        list.value = [] // 清空列表
        return
      }
      queryParams.parentId = val
      handleQuery()
    },
    {immediate: true, deep: true}
)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductBomMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (!props.parentId) {
    message.error('请选择一个ERP 产品')
    return
  }
  formRef.value.open(type, id, props.parentId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProductBomMaterial(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 批量删除ERP 产品 bom物料 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ProductApi.deleteProductBomMaterialList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ProductBomMaterial[]) => {
  checkedIds.value = records.map((item) => item.id!);
}
</script>
